import { useEffect, useState } from "react";
import { LikeOutlined, LikeFilled } from "@ant-design/icons";
import styles from "./index.module.css";
import {
  addPostLikeApi,
  deletePostLikeApi,
  getPostLikeApi,
} from "@/apis/client";
import { message } from "antd";

interface LikeButtonProps {
  initialLiked?: boolean;
  likeCount?: number;
  onLike?: (liked: boolean) => void;
  postId: any;
}

export default function LikeButton({
  initialLiked = false,
  likeCount = 0,
  onLike,
  postId,
}: LikeButtonProps) {
  const [liked, setLiked] = useState(initialLiked);
  const [count, setCount] = useState(likeCount);
  const [animating, setAnimating] = useState(false);

  async function handleClick() {
    const api = liked ? deletePostLikeApi(postId) : addPostLikeApi(postId);
    const newLiked = !liked;
    try {
      const res: any = await api;
      if (res.code === 0) {
        setLiked(newLiked);
        setCount(newLiked ? count + 1 : count - 1);
        setAnimating(true);
      } else {
        message.error("获取点赞状态失败");
      }
    } catch (error) {
      message.error("点赞失败");
    }

    if (onLike) {
      onLike(newLiked);
    }

    setTimeout(() => setAnimating(false), 500);
  }

  async function getPostLike() {
    try {
      const res: any = await getPostLikeApi(postId);
      setLiked(res.data);
    } catch (error) {
      message.error("获取点赞状态失败");
    }
  }

  useEffect(() => {
    getPostLike();
    setLiked(initialLiked);
  }, [postId, initialLiked]);

  useEffect(() => {
    setCount(likeCount);
  }, [likeCount]);

  return (
    <div className={styles.likeButtonContainer}>
      <div
        className={`${styles.likeButton} ${liked ? styles.liked : ""} ${
          animating ? styles.animate : ""
        }`}
        onClick={handleClick}
      >
        {liked ? (
          <LikeFilled className={styles.likeIcon} />
        ) : (
          <LikeOutlined className={styles.likeIcon} />
        )}
      </div>
      {count > 0 && <div className={styles.likeCount}>{count}</div>}
    </div>
  );
}
